<!DOCTYPE html>
<html>
  <head>
    <title>韭菜盒子</title>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, user-scalable=no"
    />
    <link
      href="https://cdn.bootcdn.net/ajax/libs/element-ui/2.9.2/theme-chalk/index.css"
      rel="stylesheet"
    />
    <style>
      body,
      html {
        height: 100%;
        -webkit-tap-highlight-color: transparent;
      }

      div {
        margin-left: 20px;
        line-height: 28px;
      }
      .list .name,
      .amount {
        display: inline-block;
      }
      .unit,
      .amount {
        float: right;
      }
      .name {
        font-size: 14px;
      }
      .item {
        margin-top: 10px;
      }
      .el-input {
        width: 160px;
        height: 28px;
      }
      .el-input__inner {
        height: 28px;
        width: 90%;
        background-color: #eee;
      }
      .main {
        margin: 30px auto;
        width: 520px;
      }
      .footer {
        width: 520px;
        margin: 30px auto;
        text-align: center;
      }
      .footer .info {
        font-size: 12px;
        margin-top: 20px;
        color: #696666;
      }
    </style>
  </head>

  <body ontouchstart>
    <div class="main">
      <h2 style="text-align: center; color: #409eff">
        持仓金额 <span id="totalMoney"></span>
      </h2>
      <p style="font-size: 12px; color: #696666; text-align: center">
        现在填写金额按昨日净值计算，所以今日加仓的建议明日更新持仓金额
      </p>
      <div class="list"></div>
      <div class="footer">
        <button
          class="el-button el-button--primary el-button--medium"
          id="save"
        >
          保存
        </button>
        <div class="info"></div>
      </div>
    </div>
    <script src="https://cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>

    <script>
      const vscode = acquireVsCodeApi();
      const deviceId =
        Math.random().toString(16).substr(2) +
        Math.random().toString(32).substr(2);
      $(function () {
        // const fundList = ${JSON.stringify(list)};
        const list = $('.list');

        let totalEarnings = 0;
        let totalMoney = 0;
        let listStr = '';
        fundList.forEach((item) => {
          const amount = item.amount || 0;
          const str =
            '<div class="item"><div class="name">' +
            item.name +
            '</div>' +
            '<div class="amount el-input">' +
            '<input type="number" class="amountInput el-input__inner" id="' +
            item.code +
            '" value="' +
            amount +
            '" /> <span class="unit">元</span> </div>' +
            '</div>';

          listStr += str;
          const earnings = item.earnings || 0;

          totalMoney += amount;
          totalEarnings += earnings;
        });
        list.html(listStr);
        $('#totalMoney').html(totalMoney.toFixed(2));

        $('.amountInput').on('input', function (e) {
          const value = e.target.value;
          if (value.length > 7) {
            e.target.value = value.slice(0, 7);
          }
        });

        $('#save').click(() => {
          const ammountObj = {};
          fundList.forEach((item) => {
            let amount = $('#' + item.code).val();
            amount = isNaN(Number(amount)) ? 0 : Number(amount);
            if (typeof ammountObj[item.code] !== 'object') {
              ammountObj[item.code] = {};
            }
            ammountObj[item.code].amount = amount;
            const earnings = item.earnings || 0;
            ammountObj[item.code].earnings = earnings;
          });

          fetchInfo(fundList, ({ Expansion, Datas }) => {
            const dates = [
              Expansion.FSRQ.substr(5, 5),
              Expansion.GZTIME.substr(5, 5),
            ];
            const result = [];
            totalMoney = 0;
            Datas.forEach((item) => {
              const amount = ammountObj[item.FCODE].amount;
              const obj = {
                code: item.FCODE,
                name: item.SHORTNAME,
                amount: amount,
                earnings: ammountObj[item.FCODE].earnings,
                price: item.NAV, // 净值
                priceDate: item.PDATE, // 净值时间
                isUpdated: item.PDATE.substr(5, 5) === item.GZTIME.substr(5, 5),
              };
              totalMoney += amount;
              result.push(obj);
            });
            $('#totalMoney').html(totalMoney.toFixed(2));
            // 和 vscode webview 通信
            vscode.postMessage({
              command: 'success',
              text: JSON.stringify(result),
            });
          });
        });

        if (totalEarnings !== 0) {
          const color = totalEarnings > 0 ? '#f55151' : 'green';
          let str =
            '估算收益为： <span style="font-size:16px;color:' +
            color +
            '">' +
            totalEarnings +
            '</span>，继续加油💪！';
          if (totalEarnings >= 666) {
            str +=
              '&nbsp;恭喜吃肉，老板 <span style="color:#409EFF;cursor:pointer" id="donate">打赏</span> 一下！';
          }
          $('.footer .info').html(str);

          $('#donate').click(function () {
            vscode.postMessage({
              command: 'donate',
              text: '打赏',
            });
          });
        }
      });

      function fetchInfo(fundList, cb) {
        const params = {
          pageIndex: 1,
          pageSize: fundList.length,
          plat: 'Android',
          appType: 'ttjj',
          product: 'EFund',
          Version: 1,
          deviceid: deviceId,
          Fcodes: fundList
            .reduce((arr, item) => [...arr, item.code], [])
            .join(','),
        };
        if (!params.deviceid || !params.Fcodes) return;

        const paramsArr = [];
        for (let key in params) {
          if (key && params[key]) {
            paramsArr.push(key + '=' + params[key]);
          }
        }

        window
          .fetch(
            'https://fundmobapi.eastmoney.com/FundMNewApi/FundMNFInfo?' +
              paramsArr.join('&')
          )
          .then((res) => {
            if (res.status !== 200) {
              console.log('获取数据失败');
              vscode.postMessage({
                command: 'alert',
                text: '获取数据失败',
              });
              return;
            }
            res.json().then(function (d) {
              cb(d);
            });
          });
      }
    </script>
  </body>
</html>
